/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.emex.app.stuff.report;

import com.emex.app.shared.data.Orders;
import com.emex.app.shared.data.wrapper.OrderStatusWrapper;
import com.emex.app.stuff.gui.OrderDialog;
import com.emex.app.stuff.gui.model.OrderReportTableModel;
import com.emex.app.stuff.gui.model.OrdersTableModel;
import com.emex.app.stuff.provider.OrderDataProvider;
import com.emex.app.stuff.utils.OrderStatusTableCellRenderer;
import com.emex.app.stuff.utils.ReportGenerator;
import com.emex.app.stuff.utils.UIUtils;
import java.util.ArrayList;
import java.util.List;
import net.sf.jasperreports.engine.JasperPrint;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.emex.app.stuff.report//OrderReport//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "OrderReportTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_NEVER
)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.emex.app.stuff.report.OrderReportTopComponent")
@ActionReference(path = "Menu/Отчетность" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_OrderReportAction",
        preferredID = "OrderReportTopComponent"
)
@Messages({
    "CTL_OrderReportAction=Отчеты по заказам",
    "CTL_OrderReportTopComponent=Отчеты по заказам",
    "HINT_OrderReportTopComponent=Отчеты по заказам"
})
public final class OrderReportTopComponent extends TopComponent {

    public OrderReportTopComponent() {
        initComponents();
        setName(Bundle.CTL_OrderReportTopComponent());
        setToolTipText(Bundle.HINT_OrderReportTopComponent());
        orderReportTable.setHorizontalScrollEnabled(true);
        orderReportTable.setColumnControlVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        startDatePicker = new org.jdesktop.swingx.JXDatePicker();
        applyFilterButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        endDatePicker = new org.jdesktop.swingx.JXDatePicker();
        jScrollPane1 = new javax.swing.JScrollPane();
        orderReportTable = new org.jdesktop.swingx.JXTable();
        jPanel2 = new javax.swing.JPanel();
        genPurPricesLabel = new javax.swing.JLabel();
        genPricesLabel = new javax.swing.JLabel();
        profitLabel = new javax.swing.JLabel();
        medNacenkaLabel = new javax.swing.JLabel();
        ostatokLabel = new javax.swing.JLabel();
        printTableButton = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.jPanel1.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(applyFilterButton, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.applyFilterButton.text")); // NOI18N
        applyFilterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyFilterButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.jLabel2.text")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, 0)
                        .addComponent(applyFilterButton))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(startDatePicker, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                            .addComponent(endDatePicker, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(endDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(applyFilterButton)
                .addContainerGap())
        );

        orderReportTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                orderReportTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(orderReportTable);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.jPanel2.border.title"))); // NOI18N

        genPurPricesLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(genPurPricesLabel, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.genPurPricesLabel.text")); // NOI18N

        genPricesLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(genPricesLabel, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.genPricesLabel.text")); // NOI18N

        profitLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(profitLabel, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.profitLabel.text")); // NOI18N

        medNacenkaLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(medNacenkaLabel, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.medNacenkaLabel.text")); // NOI18N

        ostatokLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(ostatokLabel, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.ostatokLabel.text")); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(genPurPricesLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(genPricesLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(profitLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(medNacenkaLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                    .addComponent(ostatokLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(genPurPricesLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(genPricesLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(profitLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(medNacenkaLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ostatokLabel)
                .addContainerGap())
        );

        printTableButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/print.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(printTableButton, org.openide.util.NbBundle.getMessage(OrderReportTopComponent.class, "OrderReportTopComponent.printTableButton.text")); // NOI18N
        printTableButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printTableButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(printTableButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(printTableButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                .addGap(16, 16, 16))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void applyFilterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyFilterButtonActionPerformed
        if (null == startDatePicker.getDate()) {
            UIUtils.showErrorMessage("Выберите дату начала");
            return;
        }
        if (null == endDatePicker.getDate()) {
            UIUtils.showErrorMessage("Выберите дату окончания");
            return;
        }
        List<Orders> orders = OrderDataProvider.getInstance().getOrdersByDate(startDatePicker.getDate(), endDatePicker.getDate());
        OrderReportTableModel model = new OrderReportTableModel(orders);
        orderReportTable.setModel(model);
        orderReportTable.setDefaultRenderer(OrderStatusWrapper.class, new OrderStatusTableCellRenderer());
        genPurPricesLabel.setText("Итого по закупкам: " + round(model.getGenPurPrice(), 2));
        genPricesLabel.setText("Итого по продажам: " + round(model.getGenPrice(), 2));
        profitLabel.setText("Прибыль: " + round(model.getGenPrice() - model.getGenPurPrice(), 2));
        Double nacenka = model.getGenPrice() - model.getGenPurPrice();
        Double avNacenka = nacenka / model.getGenPurPrice() * 100;
        medNacenkaLabel.setText("Средняя наценка: " + round(avNacenka, 2));
        ostatokLabel.setText("Остаток: " + round(model.getGenOstatok(), 2));
    }//GEN-LAST:event_applyFilterButtonActionPerformed

    private void orderReportTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_orderReportTableMouseClicked
        if (evt.getClickCount() == 2) {
            OrderDialog dialog = new OrderDialog(WindowManager.getDefault().getMainWindow(), true);
            dialog.setTitle("Редактирование/Просмотр заказа");
            dialog.setOrdersTableModel(new OrdersTableModel(new ArrayList()));
            dialog.setClient(null);
            dialog.setOrder(getOrderSelection());
            dialog.setLocationRelativeTo(this);
            dialog.setVisible(true);
        }
    }//GEN-LAST:event_orderReportTableMouseClicked

    private void printTableButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printTableButtonActionPerformed
        if (orderReportTable.getRowCount() > 0) {
            try {
                StringBuilder str = new StringBuilder();
                str.append(genPurPricesLabel.getText()).append("\\n")
                        .append(genPricesLabel.getText()).append("\\n")
                        .append(profitLabel.getText()).append("\\n")
                        .append(medNacenkaLabel.getText()).append("\\n")
                        .append(ostatokLabel.getText()).append("\\n");
                JasperPrint print = ReportGenerator.getInstance().generateDynamicReport(orderReportTable, str.toString());
                ReportGenerator.getInstance().showReport(print);
            } catch (Exception ex) {
                UIUtils.showErrorMessage("Произошли ошибки при печати таблицы");
            }
        }
    }//GEN-LAST:event_printTableButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton applyFilterButton;
    private org.jdesktop.swingx.JXDatePicker endDatePicker;
    private javax.swing.JLabel genPricesLabel;
    private javax.swing.JLabel genPurPricesLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel medNacenkaLabel;
    private org.jdesktop.swingx.JXTable orderReportTable;
    private javax.swing.JLabel ostatokLabel;
    private javax.swing.JButton printTableButton;
    private javax.swing.JLabel profitLabel;
    private org.jdesktop.swingx.JXDatePicker startDatePicker;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    public double round(double value, int places) {
        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }

    protected Orders getOrderSelection() {
        if (orderReportTable.getSelectedRow() > -1) {
            Orders orders = (Orders) orderReportTable
                    .getValueAt(orderReportTable.getSelectedRow(), -1);
            return orders;
        }
        return null;
    }
}
